import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from '../entity/product.entity';
import { ProductSku } from '../entity/product-sku.entity';
import { InventoryLog } from '../entity/inventory-log.entity';
import { FormatService } from '../format/format.service';
type CreateProductDTO = {
  name: string;
  description: string;
  basePrice: number;
  inventoryId: number;
  skus: Array<{
    specifications: Record<string, string>;
    price: number;
    stock: number;
    remark?: string;
  }>;
};

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(Product)
    private productRepository: Repository<Product>,
    @InjectRepository(ProductSku)
    private skuRepository: Repository<ProductSku>,

    private readonly formatService: FormatService,
    // @InjectRepository(InventoryLog)
    // private inventoryLogRepository: Repository<InventoryLog>
  ) {}

  async createProduct(dto: CreateProductDTO) {
    return this.productRepository.manager.transaction(async manager => {
      const date =  this.formatService.dateFormate(new Date(),'YYYY-MM-DD HH:mm:ss.SSSSSS')
      const product = manager.create(Product, {
        name: dto.name,
        description: dto.description,
        inventoryId: dto.inventoryId,
        basePrice: dto.basePrice,
        createdAt: date,
        updatedAt:date,
      });
       console.log('99')
      const savedProduct = await manager.save(product);
       console.log('1199')
      await Promise.all(
        dto.skus.map(async skuDto => {
          const sku = manager.create(ProductSku, {
            ...skuDto,
            product: savedProduct
          });
          console.log('00',sku)
          const savedSku = await manager.save(sku);
          console.log('33')
          // 创建初始库存记录
          const dateLog =   this.formatService.dateFormate(new Date(),'YYYY-MM-DD HH:mm:ss.SSSSSS')
          await manager.save(InventoryLog, {
            sku: savedSku,
            quantity: skuDto.stock,
            // type: 'INBOUND',
            remark: skuDto.remark || '',
            createdAt: dateLog,
            updatedAt:dateLog,
          });
        })
      );
      console.log('1111111')

      return manager.findOne(Product, {
        where: { id: savedProduct.id },
        relations: ['skus']
      });
    });
  }

  async toggleProductStatus(productId: number, isPublished: boolean) {
     console.log(productId)
    await this.productRepository.update(productId, { isPublished });
    return this.productRepository.findOneBy({ id: productId });
  }

  async updateSkuStock(skuId: number, quantity: number, operation: 'INBOUND' | 'OUTBOUND', remark?: string) {
     console.log('transaction:start-0')
    return this.skuRepository.manager.transaction(async manager => {

      const sku = await manager.findOne(ProductSku, {
        where: { id: skuId },
        lock: { mode: 'pessimistic_write' }
      });

      if (!sku) throw new Error('SKU不存在');

      // 更新库存
      const newStock = operation === 'INBOUND'
        ? sku.stock + quantity
        : sku.stock - quantity;

      if (newStock < 0) throw new Error('库存不足');

      await manager.update(ProductSku, skuId, { stock: newStock });

      // 记录库存变动
      const dateLogUpdate = this.formatService.dateFormate(new Date(),'YYYY-MM-DD HH:mm:ss.SSSSSS')
      console.log('dateLogUpdate:',dateLogUpdate)
      await manager.save(InventoryLog, {
        sku: { id: skuId },
        quantity,
        // type: operation,
        updatedAt:dateLogUpdate,
        remark
      });

      return manager.findOne(ProductSku, {
        where: { id: skuId },
        relations: ['inventoryLogs']
      });
    });
  }

  async deleteProduct(productId: number) {
    console.log('id:productId',productId)
    return this.productRepository.manager.transaction(async manager => {
      const product = await manager.findOne(Product, {
        where: { id: productId },
        relations: ['skus']
      });
      console.log('product:delete',product)
      if (!product) throw new Error('商品不存在');

      // 删除关联库存记录

      console.log('product:delete1222')

      for await (const sku of product.skus) {
        await manager.delete(InventoryLog, {

          // sku: { product: { id: productId } }

              sku: { id: sku.id }
              // skuId:prod.id
            });
      }

       console.log('product:delete22')

      // 删除SKU
      await manager.delete(ProductSku, { product: { id: productId } });

      // 删除商品
      await manager.delete(Product, { id: productId });

      return { success: true };
    });
  }

  async getProductDetails(productId: number) {
    return this.productRepository.findOne({
      where: { id: productId },
      relations: ['skus', 'skus.inventoryLogs'],
      order: { skus: { inventoryLogs: { createdAt: 'DESC' } } }
    });
  }
}
